package com.example.serverdemo.netty.device_tcp_server.handler;

import com.example.serverdemo.utils.log.PrintLogUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class BaseHandler extends ChannelInboundHandlerAdapter {
    private static final byte[] heartbeatBuf = {0x48,0x65,0x61,0x72,0x74,0x62,0x65,0x61,0x74};
    private static final String heartbeatStr = "Heartbeat";
    protected ChannelHandlerContext context;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        PrintLogUtil.printInfo(this,ctx.channel().remoteAddress() + "->已连接");
        this.context = ctx;
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        PrintLogUtil.printInfo(this,ctx.channel().remoteAddress() + "->已断开连接");
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        PrintLogUtil.printInfo(this,ctx.channel().remoteAddress() + heartbeatStr);
        ctx.channel().writeAndFlush(Unpooled.buffer().writeBytes(heartbeatBuf));
        super.userEventTriggered(ctx, evt);
    }

    public boolean writeAndFlush(byte[] data){
        try {
            this.context.channel().writeAndFlush(Unpooled.buffer().writeBytes(data));
            return true;
        }catch (Exception e){
            PrintLogUtil.printError(this,e);
        }
        return false;
    }
}
